package select;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import neural.Individual;

public class Rest implements Selection{

	@Override
	public List<Individual> select(List<Individual> individuals, int amount, Comparator<Individual> comparator) {
		
		Map<Individual,FitnessValues> fitnessMap  = new HashMap<Individual,FitnessValues>();
		
		//Set the fitness for every individual and calculate the total fitness
		Double totalFitness = 0.0;
		System.out.println("individuals " + individuals);
		for(Individual individual: individuals){
			fitnessMap.put(individual, new FitnessValues(individual.getFitness()));
			totalFitness += individual.getFitness();
		}
		
		List<Individual> selected = new ArrayList<Individual>();
		
		//Set the relative and acumulated fitness;
		Individual previous = null;
		for(Individual individual: individuals){
			Double aux = fitnessMap.get(individual).getFitness()/totalFitness;
			fitnessMap.get(individual).setRelativeFrequency(aux);
			if(previous == null){
				fitnessMap.get(individual).setAcumulatedFrequency(aux);
			}else{
				Double acumulated = fitnessMap.get(previous).getAcumulatedFrequency();
				fitnessMap.get(individual).setAcumulatedFrequency(acumulated + aux);
			}
			previous = individual;
			
			for(int i = 0; i < (int) (aux * amount); ++i){
				selected.add(individual);
			}
			
		}
		if(selected.size() < amount){
			Roulette roulette = new Roulette();
			roulette.selectRandomly(fitnessMap, amount,selected);
		}
		return selected;
		
	}

}
